//
//  UIApplication+Scheme.m
//  JQKit
//
//  Created by JQZ on 2017/12/28.
//  Copyright © 2017年 JQZ. All rights reserved.
//

#import "UIApplication+Scheme.h"
#import "ShortcutMacros.h"
#import "UIUtility.h"

@implementation UIApplication (Scheme)

- (void)openScheme:(NSString *)scheme
{
    if (scheme == nil || [scheme length] == 0) {
        return;
    }
    
    if (@available(iOS 10.0, *)) {
        [self openURL:URL(scheme) options:@{} completionHandler:^(BOOL success) {
#ifdef DEBUG
            NSLog(@"Open %@: %d",scheme,success);
#endif
        }];
    }
    else {
        BOOL success = [self openURL:URL(scheme)];
#ifdef DEBUG
        NSLog(@"Open %@: %d",scheme,success);
#endif
    }
}

+ (void)callApplicationSettings
{
    NSString *scheme = UIApplicationOpenSettingsURLString;
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:URL(scheme)]) {
        [app openScheme:scheme];
    }
    else {
        // 手机客户端不支持此功能
        [UIUtility showAlertWithTitle:@"不支持该功能" message:@"您的设备可能不支持应用设置功能" cancelButtonTitle:@"确定"];
    }
}

+ (void)callTelWithPhoneNumber:(NSString *)phoneNumber
{
    UIApplication *app = [UIApplication sharedApplication];
    NSString *scheme = [NSString stringWithFormat:@"tel://%@",phoneNumber];
    if ([app canOpenURL:URL(scheme)]) {
        [app openScheme:scheme];
    }
    else {
        // 手机客户端不支持此功能
        [UIUtility showAlertWithTitle:@"不能拨打该电话" message:@"您的设备可能不支持电话功能" cancelButtonTitle:@"确定"];
    }
}

+ (void)callEmailWithEmail:(NSString *)email
{
    UIApplication *app =[UIApplication sharedApplication];
    NSString *scheme = [NSString stringWithFormat:@"mailto://%@",email];
    if ([app canOpenURL:URL(scheme)]) {
        [app openScheme:scheme];
    }
    else {
        // 手机客户端不支持此功能
        [UIUtility showAlertWithTitle:@"不能打开邮件客户端" message:@"您的设备可能不支持邮件功能" cancelButtonTitle:@"确定"];
    }
}

+ (void)callWebBrowserWithURL:(NSString *)url
{
    UIApplication *app = [UIApplication sharedApplication];
    if ([app canOpenURL:URL(url)]) {
        [app openScheme:url];
    }
    else {
        // 手机客户端不支持此功能
        [UIUtility showAlertWithTitle:@"不能打开该网站" message:@"您的网址可能不正确" cancelButtonTitle:@"确定"];
    }
}

@end
